﻿using System;
using System.Configuration;
using MongoDB.Driver;
using YmtSystem.CrossCutting;

namespace YmtAuth.Repository.Mongodb
{
    public class DbContext
    {
        //private /*static*/ readonly ThreadLocal<MongoServer> pool = new ThreadLocal<MongoServer>();
        private MongoServer server;
        private string urlKey;
        private MongodbContext_NewCore contextNewCore;


        /// <summary>
        /// 初始化DbContext
        /// </summary>
        /// <param name="connectionKey">连接字符窜KEY，如果未指定则使用默认的连接字符</param>
        public DbContext(string connectionKey)
        {
            this.urlKey = connectionKey;
            this.server = InitMongoServer(urlKey);
            this.contextNewCore = new MongodbContext_NewCore(InitMongoClient(urlKey));
        }

        /// <summary>
        /// 获取强类型集合
        /// </summary>       
        public MongoCollection<T> GetTypeCollection<T>(string databaseName, string collectionName)
        {
            return ServerContext.GetDatabase(databaseName).GetCollection<T>(collectionName);
        }
        public MongoCollection<T> GetTypeCollection<T>(string databaseName, string collectionName,MongoCollectionSettings settings)
        {
            return ServerContext.GetDatabase(databaseName).GetCollection<T>(collectionName,settings);
        }
        /// <summary>
        /// Mongo 系统集合
        /// </summary>  
        public MongoCollection GetCollection(string databaseName, string collectionName)
        {
            return ServerContext.GetDatabase(databaseName).GetCollection(collectionName);
        }
        public MongoCollection GetCollection(string databaseName, string collectionName,MongoCollectionSettings settings)
        {
            return ServerContext.GetDatabase(databaseName).GetCollection(collectionName, settings);
        }
        /// <summary>
        ///  服务上下文
        /// </summary>       
        public MongoServer ServerContext
        {
            get
            {
                return this.server;
            }
        }

        public MongodbContext_NewCore ContextNewCore
        {
            get
            {
                if (this.contextNewCore == null) 
                    throw new NullReferenceException("ContextNewCore not init.");
                return this.contextNewCore;
            }
        }

        private MongoClient InitMongoClient(string mongoUrlKey)
        {
            try
            {
                if (string.IsNullOrEmpty(mongoUrlKey))
                    throw new ArgumentNullException("mongo url is null,key =" + mongoUrlKey);
                var _url = ConfigurationManager.AppSettings[mongoUrlKey];
                if (string.IsNullOrEmpty(_url))
                    throw new ArgumentNullException("mongo url is null,key =" + mongoUrlKey);
                return new MongoClient(MongoClientSettings.FromUrl(MongoUrl.Create(_url)));
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error("初始化mongo错误 {0}", ex.ToString());
                throw;
            }
        }

        private MongoServer InitMongoServer(string mongoUrlKey)
        {
            try
            {
                return InitMongoClient(mongoUrlKey).GetServer();
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error("初始化mongo错误 {0}", ex.ToString());
                throw;
            }
        }
    }
}
